<?php

class TradeModel extends Model{

    public $Model = array();

    public function _initialize(){
        $this->Model['Orders'] = new OrdersModel();
        $this->Model['Currency'] = new CurrencyModel();
        $this->Model['Finance'] = new FinanceModel();
    }

    //获取K线
    public function getKline($base_time,$currency_id,$trade_currency_id){
        $time=time()-$base_time*60*60;
        for ($i=0;$i<60;$i++){
            $start= $time+$base_time*60*$i;
            $end=$start+$base_time*60;
            //时间
            $ktime  = $start*1000+8*3600*1000;
            $item[$i][]=$ktime;
            // $item[$i][]=date('Y-m-d',$start);
            $where['currency_id']=$currency_id;
            $where['currency_trade_id']=$trade_currency_id;
            $where['type']='buy';
            $where['add_time']=array('between',array($start,$end));

            //开盘
            $where_price['currency_id']=$currency_id;
            $where_price['type']='buy';
            $where_price['add_time']=array('elt',$end);

            $order_k=$this->field('price')->where($where_price)->order('add_time desc')->find();
            $open=!empty($order_k['price'])?floatval($order_k['price']):0;
            $item[$i][]=number_format($open,8);
            //最高
            $max=$this->where($where)->max('price');
            $max=!empty($max)?floatval($max):$order_k['price'];
            $max=!empty($max)?$max:0;
            $item[$i][]=number_format($max,8);
            //最低
            $min=$this->where($where)->min('price');
            $min=!empty($min)?floatval($min):$order_k['price'];
            $min=!empty($min)?$min:0;
            $item[$i][]=number_format($min,8);
            //收盘
            $order_s=$this->field('price')->where($where)->order('add_time asc')->find();
            $order_s=!empty($order_s['price'])?floatval($order_s['price']):$order_k['price'];
            $close=!empty($order_s)?$order_s:0;
            $item[$i][]=number_format($close,8);
            //交易量
            $num=$this->where($where)->sum('num');
            $num=!empty($num)?floatval($num):0;
            $item[$i][]=number_format($num,8);
            
        }
        // $item=json_encode($item,true);
        return $item;
    }
    /**
     * [getMarkets 获得交易市场]
     * @return [type] [description]
     */
    public function getMarkets(){
        $time=time();
        $old_time=strtotime(date('Y-m-d',$time));
        $currency = $this->Model['Currency']->getMarket();
        foreach ($currency as $key => $value) {
            if($value['trade_currency_id']==0){
                $trade_currency_mark = 'CNY';
            }else{
                $trade_currency_mark = $this->Model['Currency']->where(array('currency_id'=>$value['trade_currency_id']))->getField('currency_mark');
            }
            $curr = $this->Model['Currency']->field('currency_logo,currency_name,currency_mark')->where(array('currency_id'=>$value['currency_id']))->find();
            $data['currency_logo'] = $curr['currency_logo'];
            $data['currency_name'] = $curr['currency_name'];
            $data['currency_mark'] = $curr['currency_mark'];
            $data['trade_currency_mark'] = $trade_currency_mark;

            $where['currency_id']=$value['currency_id'];
            $where['currency_trade_id']=$value['trade_currency_id'];
            //最新价格
            $order='add_time desc';
            $rs=$this->where($where)->order($order)->find();
            $data['new_price']=$rs['price']?$rs['price']:0;
            //判断价格是升是降
            $re=$this->where($where)->where("add_time<$old_time")->order($order)->find(); //一天前的价格
            if($re['price']>$rs['price']){
                //说明价格下降
                $data['new_price_status']=0;
            }else{
                $data['new_price_status']=1;
            }

            // $re=$this->where($where)->where("add_time<$old_time")->order($order)->find();
            if ($re['price']!=0){
                $data['24H_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
                if($data['24H_change']==0){
                    $data['24H_change']=0;
                }
            }else {
                $data['24H_change']=0;
            }
            $data['url'] = url('index/market/trade',array('currency'=>$data['currency_mark'].'_'.$data['trade_currency_mark']));
            $result[$trade_currency_mark][]=$data;

        }
        return $result;
    }

    /**
     * [trade 交易]
     * @param  [type] $currencyId [description]
     * @param  [type] $type       [description]
     * @param  [type] $num        [description]
     * @param  [type] $price      [description]
     * @return [type]             [description]
     */
    public function trade($member_id,$currencyId,$trade_currency_id,$type,$num,$price){
        if ($type=='buy'){
            $trade_type='sell';
        }else {
            $trade_type='buy';
        }
        //获取操作人一个订单
        $order=$this->Model['Orders']->getFirstOrdersByMember($member_id,$type ,$currencyId,$trade_currency_id);
        //获取对应交易的一个订单
        $trade_order=$this->Model['Orders']->getOneOrders($trade_type, $currencyId,$trade_currency_id,$price);
       //如果没有相匹配的订单，直接返回
        if (empty($trade_order)){
            $r[]=true;
            return $r;
        }
        //如果有就处理订单
        $trade_num=min($num,$trade_order['num']-$trade_order['trade_num']);
        //增加本订单的已经交易的数量
        $r[]=$this->Model['Orders']->where("orders_id={$order['orders_id']}")->setInc('trade_num',$trade_num);
        $r[]=$this->Model['Orders']->where("orders_id={$order['orders_id']}")->setField('trade_time',time());
        //增加trade订单的已经交易的数量
        $r[]=$this->Model['Orders']->where("orders_id={$trade_order['orders_id']}")->setInc('trade_num',$trade_num);
        $r[]=$this->Model['Orders']->where("orders_id={$trade_order['orders_id']}")->setField('trade_time',time());
        
        //更新一下订单状态
        $r[]=$this->Model['Orders']->where("trade_num>0 and status=0")->setField('status',1);
        $r[]=$this->Model['Orders']->where("num=trade_num")->setField('status',2);

        //处理资金
        switch ($type){
           
            case 'buy':
                $trade_price=min($order['price'],$trade_order['price']);
                $trade_order_money= $trade_num*$trade_price*(1-($trade_order['fee']/100));
                $order_money= $trade_num*$trade_price;//*(1+$order['fee']);
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_id'], $trade_num*(1-($order['fee']/100)), 'inc', 'num');
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_trade_id'], $order_money, 'dec', 'forzen_num');
                
                $r[]=$this->Model['Currency']->setUserMoney($trade_order['member_id'],$trade_order['currency_id'],  $trade_num, 'dec', 'forzen_num');
                $r[]=$this->Model['Currency']->setUserMoney($trade_order['member_id'],$trade_order['currency_trade_id'], $trade_order_money, 'inc', 'num');
                
                //返还多扣除的部分
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_trade_id'], $trade_num*($order['price']-$trade_price), 'inc', 'num');
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_trade_id'], $trade_num*($order['price']-$trade_price), 'dec', 'forzen_num');
                //手续费
                $r[]=$this->Model['Finance']->addFinance($order['member_id'], 'TRADE_FEE', '交易手续费',$trade_num*($order['fee']/100), 2, $order['currency_id']);
                $r[]=$this->Model['Finance']->addFinance($trade_order['member_id'], 'TRADE_FEE', '交易手续费',$trade_num*$trade_price*($trade_order['fee']/100), 2, $order['currency_trade_id']);
                break;
            case 'sell':
                $trade_price=max($order['price'],$trade_order['price']);
                $order_money= $trade_num*$trade_price*(1-($order['fee']/100));
                $trade_order_money= $trade_num*$trade_price;//*(1+$trade_order['fee']);
              
                
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_id'], $trade_num, 'dec', 'forzen_num');
                $r[]=$this->Model['Currency']->setUserMoney($member_id,$order['currency_trade_id'], $order_money, 'inc', 'num');
                 
                $r[]=$this->Model['Currency']->setUserMoney($trade_order['member_id'],$trade_order['currency_id'], $trade_num*(1-($order['fee']/100)), 'inc', 'num');
                $r[]=$this->Model['Currency']->setUserMoney($trade_order['member_id'],$trade_order['currency_trade_id'],$trade_order_money, 'dec', 'forzen_num');
                //手续费
                $r[]=$this->Model['Finance']->addFinance($order['member_id'], 'TRADE_FEE', '交易手续费',$trade_num*$trade_price*($order['fee']/100), 2, $order['currency_trade_id']);
                $r[]=$this->Model['Finance']->addFinance($trade_order['member_id'], 'TRADE_FEE', '交易手续费',$trade_num*($trade_order['fee']/100), 2, $order['currency_id']);
                break;
        }
        //修正最终成交的价格
        $r[]=$this->Model['Orders']->where("num=trade_num and orders_id={$order['orders_id']}")->setField('price',$trade_price);
        $r[]=$this->Model['Orders']->where("num=trade_num and orders_id={$trade_order['orders_id']}")->setField('price',$trade_price);
        
        //写入成交表
        $r[]=$this->addTrade($order['member_id'], $order['currency_id'], $order['currency_trade_id'],$trade_price, $trade_num, $order['type'],($order['fee']/100),1);
        $r[]=$this->addTrade($trade_order['member_id'], $trade_order['currency_id'], $trade_order['currency_trade_id'], $trade_price, $trade_num, $trade_order['type'],($order['fee']/100),0);       
        $num =$num- $trade_num;
        if ($num>0){
            //递归
            $r[]= $this->trade($member_id,$currencyId,$trade_currency_id, $type, $num, $price);
        }
        return $r;
    }


    /**
     * 增加交易记录
     * @param unknown $member_id
     * @param unknown $currency_id
     * @param unknown $currency_trade_id
     * @param unknown $price
     * @param unknown $num
     * @param unknown $type
     * @return boolean
     */
    private function  addTrade($member_id,$currency_id,$currency_trade_id,$price,$num,$type,$fee,$status=0){
        switch ($type){
            case 'buy':$fee=$num*$fee;break;
            case 'sell':$fee=$price*$num*$fee;break;
            default:$fee=0;
        }
        $data=array(
            'member_id'=>$member_id,
            'currency_id'=>$currency_id,
            'currency_trade_id'=>$currency_trade_id,
            'price'=>$price,
            'num'=>$num,
            'fee'=>$fee,
            'money'=>$price*$num,
            'type'=>$type,
            'add_time'=>time(),
            'status'=>$status
        );
        if ($this->create($data)){
            if ($this->add()){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    /**
      * 返回最高价
     @param int $currency_id 币种ID
      */
    public function getMaxPriceTrade($currency_id,$trade_currency_id){
        $order='desc';
        $trade= $this->getTradeByPrice($currency_id,$trade_currency_id,$order);
        return $trade['price'];
    }
     /**
      * 返回最低价
      @param int $currency_id 币种ID
      */
    public function getminPriceTrade($currency_id,$trade_currency_id){
        $order='asc';
        $trade= $this->getTradeByPrice($currency_id,$trade_currency_id,$order);
        return $trade['price'];
    }
    /**
      * 指定价格一个成交记录
      * @param int $currency_id 币种ID
      * @param char $order 排序
      */
    public function getTradeByPrice($currency_id,$trade_currency_id,$order){
        $where['currency_id']=$currency_id;
        $where['currency_trade_id']=$trade_currency_id;
        return $this->field('price')->where($where)->order('price '.$order)->find();

    }

    /**
      * 获取指定数量的成交记录
      * @param int $num
      */
    public function getTradesByNum($num,$currency_id,$trade_currency_id,$status=0){
        $where['currency_id']=$currency_id;
        $where['currency_trade_id']=$trade_currency_id;
        $where['status']=$status;
        $data = $this->where($where)->order('add_time desc,trade_id desc')->limit($num)->select();
        foreach ($data as $key => $value) {
            $data[$key]['addtime'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        return $data;
    }

    /**
     * 获取当前币种的信息
     * @param int $id 币种id
     * @return 24H成交量 24H_done_num  24H成交额 24H_done_money 24H涨跌 24H_change 7D涨跌  7D_change
     * @return 最新价格 new_price 买一价 buy_one_price 卖一价 sell_one_price 最高价 max_price 最低价 min_price
     */
    public function getCurrencyMessageById($currency_id,$trade_currency_id){
        $where['currency_id']=$currency_id;
        $where['currency_trade_id']=$trade_currency_id;
        $time=time();
        //一天前的时间
        $old_time=strtotime(date('Y-m-d',$time));
        //最新价格
        $order='add_time desc';
        $rs=$this->where($where)->order($order)->find();
        $data['new_price']=$rs['price']?$rs['price']:0;
        //判断价格是升是降
        $re=$this->where($where)->where("add_time<$old_time")->order($order)->find();
        if($re['price']>$rs['price']){
            //说明价格下降
            $data['new_price_status']=0;
        }else{
            $data['new_price_status']=1;
        }
        //24H涨跌
        // $re=$this->where($where)->where("add_time<$time-60*60*24")->order($order)->find();
        if ($re['price']!=0){
            $data['24H_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
            if($data['24H_change']==0){
                $data['24H_change']=0;
            }
        }else {
            $data['24H_change']=0;
        }
        //7D涨跌
        $re=$this->where($where)->where("add_time<$time-60*60*24*7")->order($order)->find();
        if ($re['price']!=0){
            $data['7D_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
            if($data['7D_change']==0){
                $data['7D_change']=0;
            }
        }else {
            $data['7D_change']=0;
        }
        //24H成交量
        $rs=$this->field('num')->where($where)->where("add_time>$time-60*60*24")->sum('num');
        $data['24H_done_num']=$rs;
        //24H成交额
        $rs=$this->field('num*price')->where($where)->where("add_time>$time-60*60*24")->sum('num*price');
        $data['24H_done_money']=$rs;
        //最低价
        $data['min_price']=$this->getminPriceTrade($currency_id,$trade_currency_id);
        //最高价
        $data['max_price']=$this->getmaxPriceTrade($currency_id,$trade_currency_id);
        //买一价
        $data['buy_one_price']=$this->Model['Orders']->getOneOrdersByPrice($currency_id,$trade_currency_id, 'buy');
        //卖一价
        $data['sell_one_price']=$this->Model['Orders']->getOneOrdersByPrice($currency_id,$trade_currency_id, 'sell');
        //返回
        return $data;
    }
    
}